import tkinter as tk
from tkinter import messagebox
import sqlite3


class StudentManagementSystem:
    def __init__(self, master):
        self.master = master
        self.master.title("学生信息管理系统")

        # 计算主界面窗口的位置使其居中显示
        window_width = 280
        window_height = 140
        screen_width = self.master.winfo_screenwidth()
        screen_height = self.master.winfo_screenheight()
        x_coordinate = (screen_width - window_width) // 2
        y_coordinate = (screen_height - window_height) // 2
        self.master.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")

        self.create_database_connection()
        self.create_login_interface()

        self.add_window = None
        self.delete_window = None
        self.modify_window = None
        self.query_window = None

    def create_database_connection(self):
        self.conn = sqlite3.connect("student_info.db")
        self.c = self.conn.cursor()
        self.c.execute('''CREATE TABLE IF NOT EXISTS students (
                            id INTEGER PRIMARY KEY,
                            student_id INTEGER,
                            name TEXT,
                            gender TEXT,
                            phone TEXT)''')
        self.conn.commit()

    def create_login_interface(self):
        self.login_frame = tk.Frame(self.master)
        self.login_frame.pack(pady=20)

        self.label_username = tk.Label(self.login_frame, text="用户名：")
        self.label_username.grid(row=0, column=0, padx=5, pady=5)
        self.entry_username = tk.Entry(self.login_frame)
        self.entry_username.grid(row=0, column=1, padx=5, pady=5)

        self.label_password = tk.Label(self.login_frame, text="密码：")
        self.label_password.grid(row=1, column=0, padx=5, pady=5)
        self.entry_password = tk.Entry(self.login_frame, show="*")
        self.entry_password.grid(row=1, column=1, padx=5, pady=5)

        self.button_login = tk.Button(self.login_frame, text="登录", command=self.login)
        self.button_login.grid(row=2, columnspan=2, padx=5, pady=5)

    def login(self):
        # 用户名和密码都是 admin
        if self.entry_username.get() == "admin" and self.entry_password.get() == "admin":
            self.show_main_interface()
        else:
            messagebox.showerror("错误", "用户名或密码错误！")

    def show_main_interface(self):
        self.login_frame.destroy()

        self.main_frame = tk.Frame(self.master)
        self.main_frame.pack(pady=20)

        self.button_add = tk.Button(self.main_frame, text="增加学生信息", command=self.open_add_window)
        self.button_add.grid(row=0, column=0, padx=5, pady=5)

        self.button_delete = tk.Button(self.main_frame, text="删除学生信息", command=self.open_delete_window)
        self.button_delete.grid(row=0, column=1, padx=5, pady=5)

        self.button_modify = tk.Button(self.main_frame, text="修改学生信息", command=self.open_modify_window)
        self.button_modify.grid(row=1, column=0, padx=5, pady=5)

        self.button_query = tk.Button(self.main_frame, text="查询学生信息", command=self.open_query_window)
        self.button_query.grid(row=1, column=1, padx=5, pady=5)

    def open_add_window(self):
        if not self.add_window:
            self.add_window = tk.Toplevel()
            self.add_window.title("添加学生信息")
            self.add_window.resizable(False, False)
            self.add_window.protocol("WM_DELETE_WINDOW", self.close_add_window)

            # 计算窗口位置使其居中显示
            window_width = 250
            window_height = 180
            screen_width = self.add_window.winfo_screenwidth()
            screen_height = self.add_window.winfo_screenheight()
            x_coordinate = (screen_width - window_width) // 2
            y_coordinate = (screen_height - window_height) // 2
            self.add_window.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")

            self.create_add_window_widgets()

        self.add_window.lift()

    def close_add_window(self):
        self.add_window.destroy()
        self.add_window = None

    def create_add_window_widgets(self):
        self.label_student_id = tk.Label(self.add_window, text="学号：")
        self.label_student_id.grid(row=0, column=0, padx=5, pady=5)
        self.entry_student_id = tk.Entry(self.add_window)
        self.entry_student_id.grid(row=0, column=1, padx=5, pady=5)

        self.label_name = tk.Label(self.add_window, text="姓名：")
        self.label_name.grid(row=1, column=0, padx=5, pady=5)
        self.entry_name = tk.Entry(self.add_window)
        self.entry_name.grid(row=1, column=1, padx=5, pady=5)

        self.label_gender = tk.Label(self.add_window, text="性别：")
        self.label_gender.grid(row=2, column=0, padx=5, pady=5)
        self.entry_gender = tk.Entry(self.add_window)
        self.entry_gender.grid(row=2, column=1, padx=5, pady=5)

        self.label_phone = tk.Label(self.add_window, text="手机号：")
        self.label_phone.grid(row=3, column=0, padx=5, pady=5)
        self.entry_phone = tk.Entry(self.add_window)
        self.entry_phone.grid(row=3, column=1, padx=5, pady=5)

        self.button_submit = tk.Button(self.add_window, text="提交", command=self.submit_student)
        self.button_submit.grid(row=4, columnspan=2, padx=5, pady=5)

    def submit_student(self):
        student_id = self.entry_student_id.get()
        name = self.entry_name.get()
        gender = self.entry_gender.get()
        phone = self.entry_phone.get()
        if self.entry_name.get() == '' or self.entry_student_id.get() == '' or self.entry_gender.get() == '' or self.entry_phone.get() == '':
            messagebox.showinfo("失败", "学生信息不能为空！")
        else:
            messagebox.showinfo("成功", "学生信息添加成功！")
            self.c.execute("INSERT INTO students (student_id, name, gender, phone) VALUES (?, ?, ?, ?)",
                           (student_id, name, gender, phone))
            self.conn.commit()
            self.close_add_window()

    def open_delete_window(self):
        if not self.delete_window:
            self.delete_window = tk.Toplevel()
            self.delete_window.resizable(False, False)
            self.delete_window.title("删除学生信息")
            self.delete_window.protocol("WM_DELETE_WINDOW", self.close_delete_window)

            # 计算窗口位置使其居中显示
            window_width = 370
            window_height = 260
            screen_width = self.delete_window.winfo_screenwidth()
            screen_height = self.delete_window.winfo_screenheight()
            x_coordinate = (screen_width - window_width) // 2
            y_coordinate = (screen_height - window_height) // 2
            self.delete_window.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")

            self.create_delete_window_widgets()

        self.delete_window.lift()

    def close_delete_window(self):
        self.delete_window.destroy()
        self.delete_window = None

    def create_delete_window_widgets(self):
        self.listbox_students = tk.Listbox(self.delete_window, selectmode=tk.MULTIPLE, width=50, height=10)
        self.listbox_students.grid(row=0, column=0, columnspan=2, padx=5, pady=5)

        self.populate_student_listbox()

        self.button_delete = tk.Button(self.delete_window, text="删除", command=self.delete_students_from_db)
        self.button_delete.grid(row=1, columnspan=2, padx=5, pady=5)

    def populate_student_listbox(self):
        self.listbox_students.delete(0, tk.END)
        self.c.execute("SELECT * FROM students")
        students = self.c.fetchall()
        for student in students:
            self.listbox_students.insert(tk.END, f"{student[1]} - {student[2]}")

    def delete_students_from_db(self):
        selected_indices = self.listbox_students.curselection()
        if not selected_indices:
            messagebox.showinfo("提示", "请选择要删除的学生！")
            return

        confirmation = messagebox.askyesno("确认删除", "是否要删除所选学生？")
        if confirmation:
            for index in selected_indices:
                student_id = self.listbox_students.get(index).split(" - ")[0]
                self.c.execute("DELETE FROM students WHERE student_id=?", (student_id,))
                self.conn.commit()
            messagebox.showinfo("成功", "所选学生信息删除成功！")
            self.populate_student_listbox()

    def open_modify_window(self):
        if not self.modify_window:
            self.modify_window = tk.Toplevel()
            self.modify_window.resizable(False, False)
            self.modify_window.title("修改学生信息")
            self.modify_window.protocol("WM_DELETE_WINDOW", self.close_modify_window)

            # 计算窗口位置使其居中显示
            window_width = 370
            window_height = 260
            screen_width = self.modify_window.winfo_screenwidth()
            screen_height = self.modify_window.winfo_screenheight()
            x_coordinate = (screen_width - window_width) // 2
            y_coordinate = (screen_height - window_height) // 2
            self.modify_window.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")

            self.create_modify_window_widgets()

        self.modify_window.lift()

    def close_modify_window(self):
        self.modify_window.destroy()
        self.modify_window = None

    def create_modify_window_widgets(self):
        self.listbox_students = tk.Listbox(self.modify_window, width=50, height=10)
        self.listbox_students.grid(row=0, column=0, columnspan=2, padx=5, pady=5)

        self.populate_student_listbox()

        self.button_select = tk.Button(self.modify_window, text="选择学生", command=self.select_student_to_modify)
        self.button_select.grid(row=1, columnspan=2, padx=5, pady=5)

    def select_student_to_modify(self):
        selected_index = self.listbox_students.curselection()
        if not selected_index:
            messagebox.showinfo("提示", "请选择要修改的学生！")
            return

        student_id = self.listbox_students.get(selected_index).split(" - ")[0]
        self.modify_selected_student(student_id)

    def modify_selected_student(self, student_id):
        if not self.modify_window:
            return

        self.modify_window.destroy()
        self.modify_window = None

        self.modify_window = tk.Toplevel()
        self.modify_window.resizable(False, False)
        self.modify_window.title("修改学生信息")
        self.modify_window.protocol("WM_DELETE_WINDOW", self.close_modify_window)

        # 计算窗口位置使其居中显示
        window_width = 250
        window_height = 180
        screen_width = self.modify_window.winfo_screenwidth()
        screen_height = self.modify_window.winfo_screenheight()
        x_coordinate = (screen_width - window_width) // 2
        y_coordinate = (screen_height - window_height) // 2
        self.modify_window.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")

        self.create_modify_window_widgets_for_selected_student(student_id)

        self.modify_window.lift()

    def create_modify_window_widgets_for_selected_student(self, student_id):
        self.label_student_id = tk.Label(self.modify_window, text="学号：")
        self.label_student_id.grid(row=0, column=0, padx=5, pady=5)
        self.entry_student_id = tk.Entry(self.modify_window)
        self.entry_student_id.grid(row=0, column=1, padx=5, pady=5)

        self.label_name = tk.Label(self.modify_window, text="姓名：")
        self.label_name.grid(row=1, column=0, padx=5, pady=5)
        self.entry_name = tk.Entry(self.modify_window)
        self.entry_name.grid(row=1, column=1, padx=5, pady=5)

        self.label_gender = tk.Label(self.modify_window, text="性别：")
        self.label_gender.grid(row=2, column=0, padx=5, pady=5)
        self.entry_gender = tk.Entry(self.modify_window)
        self.entry_gender.grid(row=2, column=1, padx=5, pady=5)

        self.label_phone = tk.Label(self.modify_window, text="手机号：")
        self.label_phone.grid(row=3, column=0, padx=5, pady=5)
        self.entry_phone = tk.Entry(self.modify_window)
        self.entry_phone.grid(row=3, column=1, padx=5, pady=5)

        # 填充已选学生的信息
        self.c.execute("SELECT * FROM students WHERE student_id=?", (student_id,))
        student = self.c.fetchone()
        self.entry_student_id.insert(0, student[1])
        self.entry_name.insert(0, student[2])
        self.entry_gender.insert(0, student[3])
        self.entry_phone.insert(0, student[4])

        self.button_modify = tk.Button(self.modify_window, text="修改",
                                       command=lambda: self.modify_student_in_db(student_id))
        self.button_modify.grid(row=4, columnspan=2, padx=5, pady=5)

    def modify_student_in_db(self, student_id):
        new_student_id = self.entry_student_id.get()
        name = self.entry_name.get()
        gender = self.entry_gender.get()
        phone = self.entry_phone.get()

        if self.entry_name.get() == '' or self.entry_student_id.get() == '' or self.entry_gender.get() == '' or self.entry_phone.get() == '':
            messagebox.showinfo("失败", "学生信息不能为空！")
        else:
            self.c.execute("UPDATE students SET student_id=?, name=?, gender=?, phone=? WHERE student_id=?",
                           (new_student_id, name, gender, phone, student_id))
            self.conn.commit()
            messagebox.showinfo("成功", "学生信息修改成功！")
            self.close_modify_window()

    def open_query_window(self):
        if not self.query_window:
            self.query_window = tk.Toplevel()
            self.query_window.resizable(False, False)
            self.query_window.title("查询学生信息")
            self.query_window.protocol("WM_DELETE_WINDOW", self.close_query_window)

            # 计算窗口位置使其居中显示
            window_width = 370
            window_height = 260
            screen_width = self.query_window.winfo_screenwidth()
            screen_height = self.query_window.winfo_screenheight()
            x_coordinate = (screen_width - window_width) // 2
            y_coordinate = (screen_height - window_height) // 2
            self.query_window.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")

            self.create_query_window_widgets()

        self.query_window.lift()

    def close_query_window(self):
        self.query_window.destroy()
        self.query_window = None

    def create_query_window_widgets(self):
        self.label_search = tk.Label(self.query_window, text="请输入要查询的学号或姓名：")
        self.label_search.grid(row=0, column=0, padx=5, pady=5)
        self.entry_search = tk.Entry(self.query_window)
        self.entry_search.grid(row=0, column=1, padx=5, pady=5)

        self.button_search = tk.Button(self.query_window, text="查询", command=self.query_student_in_db)
        self.button_search.grid(row=1, columnspan=2, padx=5, pady=5)

        self.query_result_text = tk.Text(self.query_window, height=10, width=50)
        self.query_result_text.grid(row=2, columnspan=2, padx=5, pady=5)

    def query_student_in_db(self):
        search_keyword = self.entry_search.get()
        self.c.execute("SELECT * FROM students WHERE student_id=? OR name=?", (search_keyword, search_keyword))
        students = self.c.fetchall()
        if students:
            self.query_result_text.delete(1.0, tk.END)
            for student in students:
                self.query_result_text.insert(tk.END,
                                              f"学号：{student[1]}\n姓名：{student[2]}\n性别：{student[3]}\n手机号：{student[4]}\n\n")
        else:
            messagebox.showinfo("提示", "未找到匹配的学生信息！")
